package com.sgcc.pda.web.receiver;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;

import com.sgcc.pda.data.entity.BaseEntity;
import com.sgcc.pda.tools.LogPrintUtils;
import com.sgcc.pda.util.NetWorkTools;

import com.sgcc.pda.util.PlatConstant;

import java.text.MessageFormat;

/**
 * @创建者：suven on 2020/3/24 10:55
 * @描述： 广播接收者
 * @版本：1.0
 * @修改人：
 * @修改时间：
 * @修改说明：
 * @修改版本：
 */
public abstract class HttpReceiver extends BroadcastReceiver implements IWebResult {

    private Context mContext;
    String mTag;

    /**
     * 注册广播
     *
     * @param context
     */
    public HttpReceiver(Context context) {
        this.mContext = context;
        this.mTag = NetWorkTools.
                getRandomBoradcastName(context);
        LogPrintUtils.d("mTag： " + mTag);
        LogPrintUtils.d("注册广播");
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(mTag);
        try {
            mContext.registerReceiver(this, intentFilter,
                    PlatConstant.IWeb.BROADCAST_PERMISSION_DISC, null);
        } catch (Exception e) {
            e.printStackTrace();
            LogPrintUtils.d("registerReceiver:异常", e);
        }
    }


    @Override
    public String getTag() {
        return mTag;
    }

    @Override
    public void onIDownLoading(int progress) {

    }


    /**
     * 接收广播内容
     *
     * @param context
     * @param intent
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        int code = intent.getIntExtra(PlatConstant.IWebState.CODE, 0);
        String result = intent.getStringExtra(PlatConstant.IWebState.INTENT_ID);
        LogPrintUtils.d(MessageFormat.format("code：{0}", code));
        LogPrintUtils.d(MessageFormat.format("result：{0}", result));
        if (code == PlatConstant.IWebState.HTTP_RESPONSE_CODE_DOWNLOADING) {
            int progress = Integer.parseInt(result);
            onIDownLoading(progress);
            return;
        }
        unregisterReceiver();
        switch (code) {
            case PlatConstant.IWebState.HTTP_RESPONSE_CODE_SUCCESS://下载成功
                if (TextUtils.isEmpty(result)) {
                    LogPrintUtils.d(String.format("接口信息返回为空 %s", PlatConstant.IWebState.none));
                    onIFail(PlatConstant.IWebState.none, "接口信息返回为空");
                } else {
                    try {
                        if (isDownLoad()) {
                            LogPrintUtils.d(String.format("成功 %s", PlatConstant.IWebState.success));
                            onISuccess(result);
                        } else {
                            BaseEntity entity = BaseEntity.objectFromData(result, BaseEntity.class);
                            if (entity != null && !TextUtils.isEmpty(entity.RT_F)) {
                                if (PlatConstant.IWebState.login_timeout.equalsIgnoreCase(entity.RT_F)) {
                                    LogPrintUtils.d(String.format("登录会话超时 %s", PlatConstant.IWebState.login_timeout));
                                    Intent sintent = new Intent();
                                    sintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    context.startActivity(sintent.setComponent(new ComponentName(PlatConstant.IWeb.PACKAGE_NAME, PlatConstant.IWeb.CLASS_NAME)));
                                    System.exit(0);
                                } else if (PlatConstant.IWebState.success.equalsIgnoreCase(entity.RT_F)) {
                                    LogPrintUtils.d(String.format("成功 %s", PlatConstant.IWebState.success));
                                    onISuccess(result);
                                } else {
                                    LogPrintUtils.d(String.format("%s  %s", entity.RT_D, entity.RT_F));
                                    onIFail(entity.RT_F, entity.RT_D);
                                }
                            } else {
                                LogPrintUtils.d(String.format("接口返回解析错误 %s", PlatConstant.IWebState.encrypterror));
                                onIFail(PlatConstant.IWebState.encrypterror, "接口返回解析错误");
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        LogPrintUtils.d(String.format("接口返回产生异常 %s", PlatConstant.IWebState.error));
                        LogPrintUtils.d(e);
                        onIFail(PlatConstant.IWebState.error, "接口返回产生异常");
                    }
                }
                break;
            case PlatConstant.IWebState.HTTP_RESPONSE_CODE_FAIL://下载失败
                LogPrintUtils.d(String.format("前置接口响应异常 %s", PlatConstant.IWebState.timeout));
                onIFail(PlatConstant.IWebState.timeout, "前置接口响应异常");
                break;
            case PlatConstant.IWebState.HTTP_RESPONSE_CODE_NO_NETWORK://无网络
                LogPrintUtils.d(String.format("现场作业终端网络信号异常 %s", PlatConstant.IWebState.neterror));
                onIFail(PlatConstant.IWebState.neterror, "现场作业终端网络信号异常");
                break;

            default:
                LogPrintUtils.d(String.format("未知错误 %s", PlatConstant.IWebState.other_error));
                onIFail(PlatConstant.IWebState.other_error, "未知错误");
                break;
        }
    }

    //是否收到信息后注消广播
    protected boolean unRegister() {
        return true;
    }

    /**
     * 接触广播
     */
    private void unregisterReceiver() {
        LogPrintUtils.d("unregisterReceiver");
        try {
            if (unRegister())
                mContext.unregisterReceiver(this);
            LogPrintUtils.d(String.format("unRegister()：%s", unRegister()));
        } catch (Exception e) {
            e.printStackTrace();
            LogPrintUtils.d("unregisterReceiver:异常", e);
        }
    }
}
